package com.lzyjkz.quick_auth.service.impl;

import cn.hutool.json.JSONObject;
import com.lzyjkz.quick_auth.service.OAuthUserService;
import com.lzyjkz.quick_system.entity.SysOauthInfo;
import com.lzyjkz.quick_system.entity.SysUser;
import com.lzyjkz.quick_system.security.SysUserDetails;
import com.lzyjkz.quick_system.service.SysOauthInfoService;
import com.lzyjkz.quick_system.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
@RequiredArgsConstructor
public class OAuthUserServiceImpl implements OAuthUserService {

    private final SysUserService sysUserService;
    private final SysOauthInfoService sysOauthInfoService;
    private final PasswordEncoder passwordEncoder;

    @Override
    public boolean existUser(JSONObject userInfo, String platform) {
        return sysOauthInfoService.existUserByIdAndPlatform(userInfo.getStr("id"), platform);
    }

    @Override
    public UserDetails getUserDetails(JSONObject userInfo, String platform) {
        SysUser user = sysOauthInfoService.findUserByIdAndPlatform(userInfo.getStr("id"), platform);
        return new SysUserDetails(user);
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public boolean saveUser(JSONObject userInfo, String platform) {
        SysUser sysUser = new SysUser();
        sysUser.setUsername(userInfo.getStr("login") + "@" + platform);
        sysUser.setNickname(userInfo.getStr("login"));
        sysUser.setPassword(passwordEncoder.encode(UUID.randomUUID().toString()));
        sysUser.setAvatar(userInfo.getStr("avatar_url"));
        sysUserService.save(
                sysUser
        );

        SysOauthInfo sysOauthInfo = new SysOauthInfo();
        sysOauthInfo.setInfo(userInfo.toString());
        sysOauthInfo.setUserId(sysUser.getId());
        sysOauthInfo.setPlatform(platform);
        sysOauthInfo.setStatus(0);
        sysOauthInfoService.save(
                sysOauthInfo
        );
        return true;
    }

    @Override
    public boolean updateUser(JSONObject userInfo, String platform) {
        SysOauthInfo sysOauthInfo = sysOauthInfoService.findByIdAndPlatform(userInfo.getStr("id"), platform);
        sysOauthInfo.setInfo(userInfo.toString());
        return sysOauthInfoService.updateById(sysOauthInfo);
    }

    @Override
    public boolean deleteUser(JSONObject userInfo, String platform) {
        return false;
    }
}
